package com.ruoyi.paint.admin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.paint.admin.domain.Dto.ImportSummary;
import com.ruoyi.paint.admin.domain.ImExportDto.TqSchemetintsImport;
import com.ruoyi.paint.admin.domain.TqSchemetints;
import com.ruoyi.paint.admin.domain.result.ImportResult;
import com.ruoyi.paint.admin.service.*;
import com.ruoyi.paint.admin.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SchemeTintsDataListener implements ImportDataListener<TqSchemetintsImport> {
    private List<TqSchemetints> tqSchemetintsLists = new ArrayList<>();
    private static final int BATCH_COUNT = 100;
    private List<TqSchemetintsImport> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private ITqCarsService tqCarsService;
    private TqColorschemesService tqColorschemesService;
    private TqSchemetintsService tqSchemetintsService;
    private TqTintsService tqTintsService;
    private int successCount = 0;
    private List<String> failureMessages = new ArrayList<>();
    private final ImportSummary collector;
    private ImportCallback callback;
    private String sheetName; // 新增成员变量存储Sheet名称
    public SchemeTintsDataListener(TqSchemetintsService tqSchemetintsService,
                                   TqColorschemesService tqColorschemesService,
                                   ITqCarsService tqCarsService,
                                   TqTintsService tqTintsService,ImportSummary collector,String sheetName,ImportCallback callback) {
        this.tqSchemetintsService = tqSchemetintsService;
        this.tqColorschemesService = tqColorschemesService;
        this.tqCarsService = tqCarsService;
        this.tqTintsService = tqTintsService;
        this.collector = collector;
        this.sheetName = sheetName;
        this.callback = callback;

    }


    @Override
    public void invoke(TqSchemetintsImport data, AnalysisContext context) {
        log.info("解析到一条颜色方案细节数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            flushData();
        }
    }
    List<TqSchemetintsImport> tqSchemetintsList = new ArrayList<>(cachedDataList.size());
    private void flushData() {

        for (TqSchemetintsImport importData : cachedDataList) {
            try {
                TqSchemetintsImport tqSchemetints = BeanCopyUtils.copyBean(importData, TqSchemetintsImport.class);
                tqSchemetintsList.add(tqSchemetints);
            } catch (Exception e) {
                log.error("处理颜色方案细节数据时发生错误", e);
                failureMessages.add("错误：" + importData.toString() + ", 原因：" + e.getMessage());
            }
        }
        try {
            List<TqSchemetints> tqSchemetints = BeanCopyUtils.copyBeanList(tqSchemetintsList, TqSchemetints.class);
            tqSchemetintsLists.addAll(tqSchemetints);
            successCount += tqSchemetintsList.size();
        } catch (Exception e) {
            log.error("批量保存颜色方案细节数据到数据库失败", e);
            failureMessages.add("保存失败：" + e.getMessage());
        } finally {
            cachedDataList.clear();
        }
    }

    public List<TqSchemetintsImport> getCollectedSchemeTint() {
        return tqSchemetintsList;
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!cachedDataList.isEmpty()) {
            flushData();
        }
        log.info("所有颜色方案细节数据解析完成！");
        log.info("成功导入 {} 条记录。", successCount);
        if (!failureMessages.isEmpty()) {
            log.warn("导入失败记录: {}", String.join("\n", failureMessages));
        } else {
            log.info("没有失败记录。");
        }
        // 创建当前Sheet的ImportResult实例
        ImportResult currentSheetResult = new ImportResult(successCount, failureMessages);

        // 使用collector汇总结果
        collector.addSheetResult(getSheetName(), currentSheetResult); // 这里直接添加，因为ImportResult中已包含了成功数和失败信息

        callback.onCompleted(collector);
    }

    // 返回导入结果
    public ImportResult getImportResult() {
        return new ImportResult(successCount, failureMessages);
    }

    @Override
    public String getSheetName() {
        return sheetName != null ? sheetName : "未知Sheet"; // 返回Sheet名称，如果没有设置则提供一个默认值
    }
}